package com.nulldev.util.scripting.ScriptAPI.nashorn.polyfills;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import com.nulldev.util.JVM.reflections.Reflections;
import com.nulldev.util.io.file.FileUtil;

public class NashornPolyfiller {

	public static void polyfill(final ScriptEngine se) throws ScriptException, ClassNotFoundException {
		if (!Reflections.is("jdk.nashorn.api.scripting.NashornScriptEngine"))
			return;
		if (!Reflections.get("jdk.nashorn.api.scripting.NashornScriptEngine").isInstance(se)) {
			return;
		}
		// TODO: Check if we're dealing with nashorn...
		Bindings bds = se.getBindings(ScriptContext.GLOBAL_SCOPE);
		if (bds == null) {
			se.setBindings(se.createBindings(), ScriptContext.GLOBAL_SCOPE);
			bds = se.getBindings(ScriptContext.GLOBAL_SCOPE);
		}
		se.eval(FileUtil.getResourceAsString(NashornPolyfiller.class, "nashorn-global.js"), bds);
		se.eval(FileUtil.getResourceAsString(NashornPolyfiller.class, "nashorn-promise.js"), bds);
		se.eval(FileUtil.getResourceAsString(NashornPolyfiller.class, "nashorn-setTimeout.js"), bds);
	}
}
